package com.hong.springboot.netty;

import com.hong.springboot.dao.UserMapper;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;


public class WebsocketChannelInitializer extends ChannelInitializer<SocketChannel> {


    private UserMapper userMapper;

    public WebsocketChannelInitializer(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        //基于http协议，使用http的编码和解码器
        pipeline.addLast(new HttpServerCodec());
        //是以块方式写，添加ChunkedWriteHandler处理器
        pipeline.addLast(new ChunkedWriteHandler());
        //http在传输过程中分段
        pipeline.addLast(new HttpObjectAggregator(8192));
        //心跳
        //pipeline.addLast(new IdleStateHandler(20L, 0L, 0L, TimeUnit.SECONDS));
        //将http升级为websocket
        pipeline.addLast(new WebSocketServerProtocolHandler("/hong"));
        //pipeline.addLast(new NettyServerHandler());
        pipeline.addLast(new NettyWebSocketHandler(userMapper));
    }
}